﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Diagnostics;

namespace EITSurferInfinityLib
{
    public class SerialDevice
    {
        public delegate void OnDataReceivedHandler(object sender, EventArgs e);
        public event OnDataReceivedHandler OnDataReceived;

        public SerialPort sp;
        public SerialDevice(string portName)
        {
            sp = new SerialPort();
            sp.PortName = portName;
        }

        public void Send(string msg)
        {
            sp.Write(msg+"\n");
        }

        public bool IsOpen()
        {
            return sp.IsOpen;
        }

        public void Open()
        {
            try
            {
                sp.Open();
                sp.DataReceived +=new SerialDataReceivedEventHandler(sp_DataReceived);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (OnDataReceived != null)
                OnDataReceived(null, e);
        }
        public void Close()
        {
            try
            {
                sp.Close();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
    }
}
